<template>
  <div id="manageQuestionView">
    <a-table
        :ref="tableRef"
        :columns="columns"
        :data="dataList"
        :pagination="{
        showTotal: true,
        pageSize: searchParams.pageSize,
        current: searchParams.current,
        total,
        showJumper: true,
        showPageSize: true,
      }"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
        :bordered="true"
        :stripe="true"
        size="medium"
        row-key="id"
    >
      <template #tags="{ record }">
        <a-tag v-for="(tag, index) in parseJson(record.tags)" :key="index" color="arcoblue">
          {{ tag }}
        </a-tag>
      </template>

      <template #judgeConfig="{ record }">
        <a-popover position="right">
          <template #content>
            <pre style="max-width: 400px">{{ formatJson(record.judgeConfig) }}</pre>
          </template>
          <a-button type="text" size="mini">查看配置</a-button>
        </a-popover>
      </template>

      <template #judgeCase="{ record }">
        <a-popover position="right">
          <template #content>
            <pre style="max-width: 400px">{{ formatJson(record.judgeCase) }}</pre>
          </template>
          <a-button type="text" size="mini">查看用例</a-button>
        </a-popover>
      </template>

      <template #content="{ record }">
        <a-popover position="right" :content-style="{ maxWidth: '500px' }">
          <template #content>
            <div v-html="record.content"></div>
          </template>
          <a-button type="text" size="mini">查看内容</a-button>
        </a-popover>
      </template>

      <template #answer="{ record }">
        <a-popover position="right" :content-style="{ maxWidth: '500px' }">
          <template #content>
            <div v-html="record.answer"></div>
          </template>
          <a-button type="text" size="mini">查看答案</a-button>
        </a-popover>
      </template>

      <template #acceptRate="{ record }">
        <a-tag :color="getAcceptRateColor(record)">
          {{ calculateAcceptRate(record) }}%
        </a-tag>
      </template>

      <template #createTime="{ record }">
        {{ formatTime(record.createTime) }}
      </template>

      <template #optional="{ record }">
        <a-space>
          <a-tooltip content="修改题目">
            <a-button type="primary" size="mini" @click="doUpdate(record)">
              <template #icon><icon-edit /></template>
            </a-button>
          </a-tooltip>
          <a-tooltip content="删除题目">
            <a-button status="danger" size="mini" @click="doDelete(record)">
              <template #icon><icon-delete /></template>
            </a-button>
          </a-tooltip>
        </a-space>
      </template>
    </a-table>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watchEffect } from "vue";
import {
  Page_Question_,
  Question,
  QuestionControllerService,
} from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";
import { IconEdit, IconDelete } from '@arco-design/web-vue/es/icon';

const tableRef = ref();

const dataList = ref([]);
const total = ref(0);
const searchParams = ref({
  pageSize: 10,
  current: 1,
});

const loadData = async () => {
  const res = await QuestionControllerService.listQuestionByPageUsingPost(
      searchParams.value
  );
  if (res.code === 0) {
    dataList.value = res.data.records;
    total.value = res.data.total;
  } else {
    message.error("加载失败，" + res.message);
  }
};

watchEffect(() => {
  loadData();
});

onMounted(() => {
  loadData();
});

const parseJson = (jsonStr: string) => {
  try {
    return JSON.parse(jsonStr);
  } catch (e) {
    return [];
  }
};

const formatJson = (jsonStr: string) => {
  try {
    const obj = JSON.parse(jsonStr);
    return JSON.stringify(obj, null, 2);
  } catch (e) {
    return jsonStr;
  }
};

const calculateAcceptRate = (record: Question) => {
  if (!record.submitNum || record.submitNum === 0) return 0;
  return Math.round((record.acceptedNum / record.submitNum) * 100);
};

const getAcceptRateColor = (record: Question) => {
  const rate = calculateAcceptRate(record);
  if (rate >= 70) return 'green';
  if (rate >= 30) return 'orange';
  return 'red';
};

const formatTime = (timeStr: string) => {
  if (!timeStr) return '';
  const date = new Date(timeStr);
  return date.toLocaleString();
};

const columns = [
  {
    title: "标题",
    dataIndex: "title",
    width: 150,
    ellipsis: true,
    center: true,
    tooltip: true
  },
  {
    title: "内容",
    slotName: "content",
    width: 120
  },
  {
    title: "标签",
    slotName: "tags",
    width: 150
  },
  {
    title: "答案",
    slotName: "answer",
    width: 120
  },
  {
    title: "提交数",
    dataIndex: "submitNum",
    width: 90,
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: "通过数",
    dataIndex: "acceptedNum",
    width: 90,
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: "通过率",
    slotName: "acceptRate",
    width: 100
  },
  {
    title: "判题配置",
    slotName: "judgeConfig",
    width: 120
  },
  {
    title: "判题用例",
    slotName: "judgeCase",
    width: 120
  },
  {
    title: "创建时间",
    slotName: "createTime",
    width: 180
  },
  {
    title: "操作",
    slotName: "optional",
    width: 120,
    fixed: 'right'
  }
];

const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

const onPageSizeChange = (size: number) => {
  searchParams.value = {
    ...searchParams.value,
    pageSize: size,
  };
};

const doDelete = async (question: Question) => {
  const res = await QuestionControllerService.deleteQuestionUsingPost({
    id: question.id,
  });
  if (res.code === 0) {
    message.success("删除成功");
    loadData();
  } else {
    message.error("删除失败");
  }
};

const router = useRouter();

const doUpdate = (question: Question) => {
  router.push({
    path: "/update/question",
    query: {
      id: question.id,
    },
  });
};
</script>

<style scoped>
#manageQuestionView {
  padding: 16px;
  background-color: var(--color-bg-2);
  border-radius: 4px;
}

:deep(.arco-table-th) {
  background-color: var(--color-fill-2);
}

:deep(.arco-table-tr):hover {
  background-color: var(--color-fill-1);
}
</style>
